

clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_newfirm.log"	, replace 
use 		 "$datapath/A3_age55data_WC.dta"

*=============
xtset   ym_def
*=============


{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*

*Indicate first observation and date for finding the first new job
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & newfirmid==firstnewfirmid) if newfirmid!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate)
format nvalsdate %tm

*Condtion on newfirm==1 and observred wage (post eventtime>=0 by construction)
bys lopnr (eventtime_def) : gen nvals_forwage = sum(newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid) if newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid
gen xnvalsdate_forwage = date if nvals_forwage==1 
bys lopnr (eventtime_def) : egen nvalsdate_forwage = max(xnvalsdate_forwage) // impute for all obs this value
format nvalsdate_forwage %tm


{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
{ // Generate industry indicators at 1-letter level
*===============================================================================
gen sni02 = substr(astsni02,1,2) if eventtime==0
gen sni07 = substr(astsni07,1,2) if eventtime==0

destring sni02 sni07, replace

*If both sni02 and sni07 exists, let sni07 have priority
replace sni02=. if sni07!=. & eventtime==0
replace sni02=. if sni02==0 & eventtime==0
replace sni07=. if sni07==0 & eventtime==0

*Follows the letters of SNI07 and sometimes disaggeragtes to SNI02.
gen str	SNI_1dig = "" 
replace SNI_1dig = "A" 	if inrange(sni02,1,5) | inrange(sni07,1,3)
replace SNI_1dig = "B"  if inrange(sni02,10,14) | inrange(sni07,5,9)
replace SNI_1dig = "C"  if inrange(sni02,15,33) | inrange(sni07,10,33)
replace SNI_1dig = "DE" if inrange(sni02,40,21) | inrange(sni07,35,39)
replace SNI_1dig = "F"  if inrange(sni02,45,45) | inrange(sni07,41,43)
replace SNI_1dig = "G"  if inrange(sni02,50,52) | inrange(sni07,45,47)
replace SNI_1dig = "I"  if inrange(sni02,55,55) | inrange(sni07,55,56)
replace SNI_1dig = "HJ" if inrange(sni02,60,64) | inrange(sni07,49,53) | inrange(sni07,58,63)
replace SNI_1dig = "K"  if inrange(sni02,65,67) | inrange(sni07,64,66)
replace SNI_1dig = "LMN" if inrange(sni02,70,75) | inrange(sni07,68,82)
replace SNI_1dig = "O"  if inrange(sni02,74,74) | inrange(sni07,84,84)
replace SNI_1dig = "P"  if inrange(sni02,80,80) | inrange(sni07,85,85)
replace SNI_1dig = "Q"  if inrange(sni02,85,85) | inrange(sni07,86,88)
replace SNI_1dig = "RS" if inrange(sni02,90,93) | inrange(sni07,90,96)
replace SNI_1dig = "T"  if inrange(sni02,95,95) | inrange(sni07,97,98)
replace SNI_1dig = "U"  if inrange(sni02,99,99) | inrange(sni07,99,99)

bys lopnr (SNI_1dig) : replace SNI_1dig = SNI_1dig[_N]
sort lopnr eventtime


gen newsni02 = substr(Esni021,1,2) if nvals==1
gen newsni07 = substr(Esni071,1,2) if nvals==1

destring newsni02 newsni07, replace

*If both sni02 and sni07 exists, let sni07 have priority
replace newsni02=. if newsni07!=. & nvals==1
replace newsni02=. if newsni02==0 & nvals==1
replace newsni07=. if newsni07==0 & nvals==1

*Follows the letters of SNI07 and sometimes disaggeragtes to SNI02.
gen str	newSNI_1dig = "" 
replace newSNI_1dig = "A" 	if inrange(newsni02,1,5) | inrange(newsni07,1,3)
replace newSNI_1dig = "B"  if inrange(newsni02,10,14) | inrange(newsni07,5,9)
replace newSNI_1dig = "C"  if inrange(newsni02,15,33) | inrange(newsni07,10,33)
replace newSNI_1dig = "DE" if inrange(newsni02,40,21) | inrange(newsni07,35,39)
replace newSNI_1dig = "F"  if inrange(newsni02,45,45) | inrange(newsni07,41,43)
replace newSNI_1dig = "G"  if inrange(newsni02,50,52) | inrange(newsni07,45,47)
replace newSNI_1dig = "I"  if inrange(newsni02,55,55) | inrange(newsni07,55,56)
replace newSNI_1dig = "HJ" if inrange(newsni02,60,64) | inrange(newsni07,49,53) | inrange(newsni07,58,63)
replace newSNI_1dig = "K"  if inrange(newsni02,65,67) | inrange(newsni07,64,66)
replace newSNI_1dig = "LMN" if inrange(newsni02,70,75) | inrange(newsni07,68,82)
replace newSNI_1dig = "O"  if inrange(newsni02,74,74) | inrange(newsni07,84,84)
replace newSNI_1dig = "P"  if inrange(newsni02,80,80) | inrange(newsni07,85,85)
replace newSNI_1dig = "Q"  if inrange(newsni02,85,85) | inrange(newsni07,86,88)
replace newSNI_1dig = "RS" if inrange(newsni02,90,93) | inrange(newsni07,90,96)
replace newSNI_1dig = "T"  if inrange(newsni02,95,95) | inrange(newsni07,97,98)
replace newSNI_1dig = "U"  if inrange(newsni02,99,99) | inrange(newsni07,99,99)



gen 	changeind1 = SNI_1dig!=newSNI_1dig if nvals==1
replace changeind1 = . if SNI_1dig=="" | newSNI_1dig==""





}
*
{ // Generate industry indicators at 3-digit level
*===============================================================================

*Genearte change of industry (3-digit)
*Look at missing SNI
count if (astsni07=="" & astsni02=="") & eventtime==0 // no missing sni on old job
count if (Esni071=="" & Esni021=="") & nvals==1 // 372 missing sni on new job (out of 8,576)
*Old industry SNI
gen 	xoldsni = substr(astsni07,1,3) if year>=2007 & eventtime==0
replace xoldsni = substr(astsni02,1,3) if year< 2007 & eventtime==0
bys lopnr (xoldsni) : gen oldsni = xoldsni[_N]
*New industry SNI
gen newsni = cond(Esni071=="" & year<2007, Esni021, Esni071) if nvals==1
*Change indsutry
gen changeind3= newsni!=oldsni if nvals==1 & newsni!=""
}
*
{ // Tenure on new job
*===============================================================================
*Months of tenure on new job
bys lopnr (eventtime) : egen newtenure = total(nvals!=.)
gen newtenure24 = newtenure<24
gen newtenure12 = newtenure<12

}
*

{ // Table of indiviual new job charatierics
*===============================================================================
merge m:1 persid  year using "$datapath/A0_SSYK_01_15.dta"
drop if _merge==2
gen oldocc = ssyk3 if eventtime==0
bys lopnr (oldocc) : replace oldocc = oldocc[_N]
gen newocc = ssyk3 if nvals==1
gen changeocc = newocc!=oldocc if nvals==1 & newocc!="" & oldocc!=""

foreach var of varlist rortup_new skift_new jour*_new* {
	gen D_`var' = `var'>0 & `var'!=.
	replace D_`var' = . if manl_newfirm==.
}	
eststo clear
qui eststo : xtreg changeind1	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest
qui eststo : xtreg changeind3	$instrument $linear $covariets	if nvals_forwage==1 & e(sample)==1 , cluster(varselid) fe nonest
qui eststo : xtreg changeocc	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest

esttab , keep(treat _cons) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_newjob_char.tex", 				/// 
replace keep($instrument _cons) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(treat "Above age 55" _cons "Control mean" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
nonotes postfoot("\addlinespace ") prehead("\begin{table}[htbp]\centering" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{Effect of mandated notice on job characteristics}" ///
"\begin{tabular}{l*{3}{c}}" ///
"\midrule" ///
"&(1)&(2)&(3) \\" ///
"\midrule" ///
" & \multicolumn{3}{c}{Changing} \\ " ///
"\cmidrule(lr){2-4}" ///
"& \multicolumn{1}{c}{Industry }& \multicolumn{1}{c}{Industry} & \multicolumn{1}{c}{Occupation} \\ " ///
"& \multicolumn{1}{c}{(1-digit)}& \multicolumn{1}{c}{(3-digit)} & \multicolumn{1}{c}{} \\ " ///
"\cmidrule(lr){2-4}")

eststo clear
qui eststo : xtreg newtenure	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest
qui eststo : xtreg newtenure12	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest
qui eststo : xtreg newtenure24	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest

esttab , keep(treat _cons) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_newjob_char.tex", append prefoot() /// 
keep($instrument _cons) booktabs 		///
prehead("& \multicolumn{3}{c}{Job stability} \\ " ///
"\cmidrule(lr){2-4}" ///
"& \multicolumn{1}{c}{ Tenure}& \multicolumn{1}{c}{ Seperation } & \multicolumn{1}{c}{ Seperation} \\ " ///
"& \multicolumn{1}{c}{ }& \multicolumn{1}{c}{ within 1 year } & \multicolumn{1}{c}{ within 2 years} \\ " ///
"\cmidrule(lr){2-4}" ) ///
end("\\") begin("")  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)  varlabels(treat "Above age 55" _cons "Control mean") ///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
postfoot("\addlinespace")

eststo clear		
qui eststo : xtreg D_rortup_new	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest
qui eststo : xtreg D_skift_newfirm	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest
qui eststo : xtreg D_jourberers_newfirm	$instrument $linear $covariets	if nvals_forwage==1 , cluster(varselid) fe nonest

esttab , keep(treat _cons) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_newjob_char.tex", append prefoot() /// 
keep($instrument _cons) booktabs 		///
prehead("& \multicolumn{3}{c}{Wage characteristics} \\ " ///
"\cmidrule(lr){2-4}" ///
"& \multicolumn{1}{c}{ Variable pay }& \multicolumn{1}{c}{ Shift work pay $ >0 $ } & \multicolumn{1}{c}{ On call pay $ >0 $} \\ " ///
"\cmidrule(lr){2-4}" ) ///
end("\\") begin("")  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)  varlabels(treat "Above age 55" _cons "Control mean") ///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
postfoot("\bottomrule \end{tabular} \end{table}")
}
*

{ // Graph probability of remaining at new firm
*===============================================================================
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

preserve
	keep if date>=nvalsdate
	gen atnewfirm = nvals!=. 
	bys lopnr (eventtime_def) : gen nvals2 = _n 
	
	matrix B = J(61,4,.)
	local i = 0

	forvalues t = 1(1)36{
		local i = `i' + 1
		qui xtreg atnewfirm		$instrument $linear $covariets 	if nvals2==`t' , cluster(varselid) fe nonest 

		matrix B[`i',1]  = `t' -1
		matrix B[`i',2]  = _b[_cons]
		matrix B[`i',3]  = _b[_cons] + _b[treat]
		matrix B[`i',4]  = abs(_b[treat]/_se[treat]) >=invttail(e(df_r),0.025)
	}
	svmat B
	rename B1 t
	rename B2 C
	rename B3 T
	rename B4 sig

	*Graph
	twoway (connected T t, `Tstyle') (connected C t, `Cstyle') (rspike T C t if sig==1, `Sstyle') ///
	,xline(0, lstyle(foreground) lpattern(dash) lcolor(black)) xscale(r(-0 36)) xlabel(0(6)36)  ///
	xtitle("Months after notification") ytitle("Pr(At new firm)") name(a,replace)  ///
	graphregion(color(white)) legend(order( 1 "Long notification" 2 "Short notification" ) region(color(white)))
	graph export "$agegraphpath/Event/event_RD_atnewfirm.pdf",replace

	drop t C T sig
restore

}
*


*Keep one observation per job finding
keep if nvals==1
keep 	lopnr persid date year firmid newfirmid nvalsdate firm_noemployed varselid ///
	$instrument $linear $covariets ym_def

{ // Generate new firm characteristics
*===============================================================================
*Merge on balancesheet data for old firms
merge m:1 firmid year using "$datapath/balancesheet_restricted", keepusing(inc_NetTurnover value_added  inc_opprofit profit_margin)
drop if _merge==2
drop _merge
	
*Rename variables such that it indicates old firm
rename inc_NetTurnover 	OLD_inc_NetTurnover
rename value_added	OLD_value_added
rename inc_opprofit	OLD_inc_opprofit
rename profit_margin	OLD_profit_margin
rename firm_noemployed 	OLD_firm_noemployed_RAMS

*Rename newfirmid to firmid for upcomming merge 
drop   firmid
rename newfirmid firmid
	
*Merge on characteristics of new firm	
*NOTE:  I merge on characteritics from the year before the worker finds the new
*	job, as otherwise the firm char. includes these workers and are therefore
*	endogenous.
replace year = year-1
merge m:1 firmid year using "$datapath/A1_firm_char.dta" ///
	,keepusing(firm_noemployed_RAMS firm_avg_earnings firm_share_higheduc ///
	firm_share_female firm_avg_age) 
drop if _merge==2
drop 	_merge	



*Merge on avgerage and median wages of new firm	
merge m:1 firmid year using "$datapath/A1_firm_wages.dta"
drop if _merge==2
drop 	_merge


*Merge on balancesheet data
merge m:1 firmid year using "$datapath/balancesheet_restricted", keepusing(inc_NetTurnover value_added  inc_opprofit profit_margin)
drop if _merge==2
drop _merge


*Recode year to original forma t
replace year = year+1


*Generate variables
replace firm_mean_manl = log(firm_mean_manl)
replace firm_avg_earnings = log(firm_avg_earnings)
gen firm_log_size = log(firm_avg_age)
gen log_value_added = log(value_added)
foreach var of varlist 	 inc_NetTurnover value_added inc_opprofit profit_margin firm_noemployed_RAMS {
	gen bg_`var' = `var'>OLD_`var' 	if !mi(`var') & !mi(OLD_`var')
} 

gen log_salesperworker = log(inc_NetTurnover/firm_noemployed_RAMS)
gen log_VAperworker = log(value_added/ firm_noemployed_RAMS)
gen profitperworker = inc_opprofit/ firm_noemployed_RAMS

}
*

*=========
xtset ym_def
*=========
{ // Regressions of new firm characteristics
*===============================================================================
*Panel A: indivual data
eststo clear
qui eststo: xtreg firm_mean_manl	$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg firm_avg_earnings 	$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg firm_share_female	$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg firm_avg_age		$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg firm_log_size		$instrument $linear $covariets	 , cluster(varselid) fe nonest

esttab , keep(treat _cons) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_firm_outcomes.tex", 				/// 
replace keep($instrument _cons) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(treat "Above age 55" _cons "Control mean" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
nonotes postfoot("\addlinespace ") prehead("\begin{table}[htbp]\centering" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{Effect of mandated notcie on firm sorting}" ///
"\begin{tabular}{l*{5}{c}}" ///
"\toprule" ///
"& \multicolumn{5}{c}{\textbf{Panel a:} Firm characteristics using individual-level data} \\" ///	
"\cmidrule(lr){2-6} \\" ///
"& \multicolumn{1}{c}{log(new firm wage)} & \multicolumn{1}{c}{log(new firm earnings)}  " ///
"& \multicolumn{1}{c}{Share female}& \multicolumn{1}{c}{Mean age} & \multicolumn{1}{c}{log(firm size)}  \\ " ///
"&&&&& \\ " ///
"&(1)&(2)&(3)&(4)&(5) \\" ///	
"\cmidrule(lr){2-6}")		

eststo clear
*Panel B: Balance sheet data
qui eststo: xtreg bg_inc_NetTurnover		$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg log_salesperworker		$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg log_VAperworker		$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg profitperworker		$instrument $linear $covariets	 , cluster(varselid) fe nonest
qui eststo: xtreg log_value_added		$instrument $linear $covariets	 , cluster(varselid) fe nonest


// Labels: 
//  bg_inc_NetTurnover = Sales higher in new firm compared to not. firm
// bg_inc_opprofit     = Profit higher in new firm compared to not. firm
// bg_profit_margin     = Profit/value added higher in new firm compared to not. firm
//  bg_value_added    = Value added higher in new firm compared to not. firm
//  log_va_new    = Log value added in new firm


esttab , keep(treat _cons) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats( N_clust N, fmt( %9.0fc %9.0fc))
esttab using "$agetablepath/RF/tab_firm_outcomes.tex", 				/// 
append 	keep($instrument _cons) booktabs 		///
prehead("& \multicolumn{6}{c}{\textbf{Panel b:} Firm characteristics using firm-level data} \\" ///
"\cmidrule(lr){2-6}" ///
"& \multicolumn{1}{c}{Sales new firm $ > $} & \multicolumn{1}{c}{Profit new firm $ > $}  " ///
"& \multicolumn{1}{c}{Profit/VA new firm $ > $}& \multicolumn{1}{c}{VA new firm $ > $} & \multicolumn{1}{c}{log(value added)} & \multicolumn{1}{c}{} \\ " ///
"& \multicolumn{1}{c}{Sales old firm } & \multicolumn{1}{c}{Profit old firm }  " ///
"& \multicolumn{1}{c}{Profit/VA old firm}& \multicolumn{1}{c}{VA old firm } & \multicolumn{1}{c}{} & \multicolumn{1}{c}{} \\ " ///
"&(1)&(2)&(3)&(4)&(5) \\" ///	
"\cmidrule(lr){2-6}" ) ///
end("\\") begin("")  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)  varlabels(treat "Above age 55" _cons "Control mean") ///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
postfoot("\bottomrule \end{tabular} \end{table}")
}
*
{ // RD graph log(firm size)
*===============================================================================
preserve
	*keep if eventtime_def==12
	local outcome "firm_log_size"
	
	*==========
	xtset   ym_def
	*==========

	eststo: xtreg 	`outcome'  	$instrument 	$linear  $covariets 		, cluster(varselid) fe nonest
	local b  = round(_b[$instrument] ,.001)
	local se = round(_se[$instrument] ,.001)
	
	
	gen freq=1
	
	*Residulize year*moth fixed effects
	qui areg `outcome' $covariets , absorb(ym_def)
	predict e, residuals
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `outcome'_bin = mean(`outcome')
	*tab runvar bin
	
	
	
	collapse (mean) `outcome' `outcome'_bin  (sum) freq, by(runvar bin treat)
	
	replace runvar = runvar*12
	
	*Linear Fit
	twoway 	(scatter `outcome'_bin  bin 		 	 , ms(o) mcolor(black))  		///	 	
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==0, lcolor(black)) 	 		///
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==1, lcolor(black))	 		///
		, xline(0 , lcolor(black) lpattern(dash) lstyle(foreground))  legend(off) graphregion(color(white)) 					///
		  xscale(r(-36 36)) xlabel(-36(12)36) 						///
		  xtitle("Normalized age (months)") ytitle("log(new firm size)") 	///
		  text(3.72 -24 "{&beta}=0`b'**" "(0`se')"  ,place(right)  )
	graph export "$agegraphpath/RD/RD_`outcome'.pdf", replace
restore		
}
*		
		
log close








